#include "connectform.h"
#include "ui_connectform.h"

ConnectForm::ConnectForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ConnectForm),
    port(-1),
    portIsOk(false),
    addressIsOk(false)
{
    ui->setupUi(this);
    ui->connectButton->setEnabled(false);
}

ConnectForm::~ConnectForm()
{
    delete ui;
}

void ConnectForm::on_connectButton_clicked()
{
    emit connectionAsked(address, port);
}

void ConnectForm::on_portInputText_editingFinished()
{
    QString ipPort  = ui->portInputText->text();
    QString message = "";
    QString style   = "";
    bool ok         = false;
    port            = ipPort.toInt(&ok, 10);
    portIsOk        = false;

    if( ok )
    {
        if( port < 1024 )
        {
           style    = "border: 1px solid red";
           message  = "Numéro de port invalide. Le port doit être compris entre 1024 et 65536.";
        }
        else
        {
            portIsOk = true;
        }
    }
    else
    {
        style   = "border: 1px solid red";
        message = "Numéro de port invalide";
    }

    ui->portError->setText(message);
    ui->portInputText->setStyleSheet(style);
    if( addressIsOk )
        ui->connectButton->setEnabled(portIsOk);
}

void ConnectForm::on_addressInputText_editingFinished()
{
    QString ipAddress   = ui->addressInputText->text();
    QString message = "";
    QString style   = "";
    addressIsOk     = false;

    if( ! address.setAddress( ipAddress ) )
    {
        style    = "border: 1px solid red";
        message = "Adresse Ip invalide.";
    }
    else
    {
        addressIsOk = true;
    }

    ui->addressError->setText(message);
    ui->addressInputText->setStyleSheet(style);
    if( portIsOk )
        ui->connectButton->setEnabled(addressIsOk);
}
